package com.netintech.project.system.user.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.netintech.common.utils.*;
import com.netintech.core.config.NtConfig;
import com.netintech.core.web.controller.BaseController;
import com.netintech.core.web.domain.RequestResult;
import com.netintech.project.system.user.domain.User;
import com.netintech.project.tool.build.Tcf;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 登录验证
 * 
 * @author admin
 */
@Controller
public class LoginController extends BaseController
{


    @Autowired
    private NtConfig ntConfig;

    private static final String TS = "9d53e8";

    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response)
    {
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request))
        {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }
        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public RequestResult ajaxLogin(String username, String password, Boolean rememberMe) throws Exception {
        if(ntConfig.isAuthEnabled()){
            File file = new File("a.licence");
            if(!file.exists()){
                return new RequestResult(RequestResult.Type.NO_AUTH_FILE,"证书文件不存在或证书已过期, 请上传合法证书文件。");
            }
            int i = verifyCode(file);
            if(i==1){
                return new RequestResult(RequestResult.Type.SYSTEM_UN_AUTH,"证书格式不合法，请上传合法证书文件");
            }
            if(i==2){
                return new RequestResult(RequestResult.Type.SYSTEM_UN_AUTH,"机器码不一致，请上传合法证书文件");
            }
            if(i==3){
                return new RequestResult(RequestResult.Type.SYSTEM_UN_AUTH,"授权已过期，请上传合法证书文件");
            }
        }

        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);
            return success();
        }
        catch (AuthenticationException e)
        {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    @GetMapping("/unauth")
    public String unauth()
    {
        return "error/unauth";
    }


    /**
     * 获取文件内容
     * @param file
     * @return
     */
    private String getFileContent(File file){
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempStr;
            while ((tempStr = reader.readLine()) != null) {
                sbf.append(tempStr);
            }
            reader.close();
            return sbf.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return sbf.toString();
    }

    private String getMachineCode(){
        String cpuSerial = SerialNumberUtil.getCPUSerial();
        logger.info("cpu"+cpuSerial);
        String hardDiskSN = SerialNumberUtil.getHardDiskSN();
        logger.info("hardDiskSN"+hardDiskSN);
        String motherboardSN = SerialNumberUtil.getMotherboardSN();
        logger.info("motherboardSN"+motherboardSN);
        String machineCode = "code1="+cpuSerial + "&code2="+hardDiskSN + "&code3="+motherboardSN;
        return Md5Utils.hash(machineCode+TS);
    }


    private int verifyCode(File file) throws Exception {
        String fileContent = this.getFileContent(file);
        String decrypt = CreateSecretKey.decrypt(fileContent, Tcf.K);
        String[] split = decrypt.split("&");
        String mcode = "";
        String date = "";
        String currMachineCode = this.getMachineCode();
        for(String str : split){
            String[] split1 = str.split("=");
            if(split1[0].equals("code")){
                mcode = split1[1];
            }
            if(split1[0].equals("date")){
                date = split1[1];
            }
        }
        if(StringUtils.isBlank(mcode) || StringUtils.isBlank(date)){
            return 1;
        }

        if(!currMachineCode.equals(mcode)){
            return 2;
        }
        Date td = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(td);
        long millis = simpleDateFormat.parse(format).getTime();
        if(millis>Long.valueOf(date)){
            return 3;
        }
        return 0;
    }
}
